/*
 * @author Chris
 * @since 2023/2/8 19:33
 *
 * @brief    The project will ...
 *
 * @note     ...
 *
 * @warning  Do not to ...
 *
 * Change Logs:
 *   Date           Author       Notes
 *   2023-02-08     Chris        the first version
 *
 */

#include "8052.h"

unsigned char T0RH = 0;
unsigned char T0RL = 0;

void ConfigTimer0(unsigned char ms);

void SetDACValue(unsigned char val);

extern void KeyDriver();

extern void KeyScan();

extern void I2CStart();

extern __bit I2CWrite(unsigned char dat);

extern void I2CStop();

int main() {
    EA = 1;
    ConfigTimer0(1);

    while (1) {
        KeyDriver();
    }

}

void ConfigTimer0(unsigned char ms) {
    unsigned long tmp = 65536 - 11059200 * ms / 12 / 1000 + 28;
    T0RH = tmp >> 8;
    T0RL = tmp & 0xFF;
    TH0 = T0RH;
    TL0 = T0RL;
    TMOD = TMOD & 0xF0 | 0x01;

    ET0 = 1;
    TR0 = 1;
}

void KeyAction(unsigned char key) {
    static unsigned char volt = 0;
    if (key == 0x26) {
        if (volt >= 25) {
            return;
        }
        SetDACValue(++volt * 255 / 25);
    } else if (key == 0x28) {
        if (volt <= 0) {
            return;
        }
        SetDACValue(--volt * 255 / 25);
    } else {}
}

void SetDACValue(unsigned char val) {
    I2CStart();
    if (I2CWrite(0x48 << 1)) {
        I2CStop();
        return;
    }
    I2CWrite(0x40);

    I2CWrite(val);
    I2CStop();
}

/**
 * 定时器 T0 中断服务函数
 */
void InterruptTimer0() __interrupt(1) {

    TH0 = T0RH;
    TL0 = T0RL;

    KeyScan();
}